﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Reflection;

namespace Tools.Data
{

    public class Entities
    {
        /// <summary>
        /// 自定义扩展
        /// </summary>
        private static List<SqlFuncExternal> _expMethods;
        /// <summary>
        /// 连接
        /// </summary>
        public readonly SqlSugarClient Client;

        /// <summary>
        /// 使用自定义集合
        /// </summary>
        /// <param name="sqlFuncList"></param>
        public static void UseISqlFunc(List<ISqlFunc.ISqlFunc> sqlFuncList)
        {
            _expMethods = sqlFuncList?.Select(itm => itm.SqlFuncExternal).ToList();
        }
        
        public Entities(string connectionName = null, bool iscreate = false)
        {
            var config = new ConnectionConfig
            {
                ConnectionString = ConfigurationManager.ConnectionStrings("Entities"),
                DbType = DbType.SqlServer,
                IsAutoCloseConnection = true,
            };

            if (_expMethods != null && !_expMethods.Any()) config.ConfigureExternalServices = new ConfigureExternalServices { SqlFuncServices = _expMethods };

            if (!string.IsNullOrWhiteSpace(connectionName))
            {
                var connectionString = ConfigurationManager.ConnectionStrings(connectionName);
                config.ConnectionString = connectionString;
            }

            if (iscreate)
            {
                config.InitKeyType = InitKeyType.Attribute;
            }

            Client = new SqlSugarClient(config);

        }
    }
}